import JsonSchemaEditor from "@/components/JsonSchemaForm/JsonSchemaForm.vue";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { assJsonpathData, showTips } from "@/utils/util";
import jsonpath from "jsonpath";
import { ComponentInternalInstance, defineComponent } from "vue";
import { useRoute } from "vue-router";
import { parseProfileFromDevice, parseSchemaFromDevice } from "./../../../../utils/schema";
import { GatewayType } from "@/api/interface/iot";
import { getCurrentInstance } from "vue";
import { saveDeviceConfig, saveProductConfig } from "@/api/modules/iot/variable";

/**
 * 设备参数信息,scheme中的config下面子设备参数信息（排除sensor节点）
 * 相关参数：设备接入端口、地址、采集周期、上报周期
 */
export default defineComponent({
	props: {
		type: {
			type: String,
			default() {
				return GatewayType.Device;
			}
		}
	},
	emits: [],
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		const refreshDeviceDetail = () => {
			mittBus.emit("refreshDeviceDetail");
		};
		const saveSchema = async () => {
			if (disabledMod.value) return;
			//追加原来的sensors配置
			const oldSchema = parseSchemaFromDevice(schema.value);
			// schemaTree.root.properties.sensor = oldSchema.sensor || {};
			// console.log(JSON.stringify(schemaTree.root, null, 2));
			let data = JSON.parse(JSON.stringify(schemaTree.root));
			if (oldSchema.sensor) {
				data.properties.sensor = oldSchema.sensor;
			}
			let res;
			if (route.query.productModel) {
				res = await saveProductConfig({
					id: route.query.id,
					schema: data.properties,
					data: deviceConfigProfile.value
				});
			} else {
				res = await saveDeviceConfig({
					idSn: route.query.sn || route.query.id,
					schema: data.properties,
					data: deviceConfigProfile.value
				});
			}
			let ok = showTips(res.code, proxy?.$t("common.savetips.parameter"), res.message);
			if (ok) {
				refreshDeviceDetail();
			}
		};

		//设备参数配置模型
		const schema = inject<any>(SchemaNodeKey.schema);
		const profile = inject<any>(SchemaNodeKey.profile);
		const disabledMod = inject<any>(AuthBtns.disabledMod);
		let deviceConfigSchema = ref<any>({});
		let deviceConfigProfile = ref<any>({});
		//缓存sensor数据
		const schemaTree = reactive({
			root: {
				type: "object",
				title: schema.value?.properties?.config?.title || "设备配置",
				properties: {},
				required: []
			}
		});
		// console.log(JSON.stringify(schemaTree.root, null, 2));
		// console.log(JSON.stringify(deviceConfigProfile.value, null, 2));
		onBeforeMount(() => {
			initSchema();
			//监听新增节点
			mittBus.on("addJsonValue", () => {
				saveSchema();
			});
			//监听删除节点

			mittBus.on("delJsonValue", () => {
				saveSchema();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("addJsonValue");
			mittBus.off("delJsonValue");
		});
		watch(
			() => schema.value,
			() => {
				initSchema();
			}
		);
		//初始化上报数据，没有模型就自动增加
		const initSchema = () => {
			deviceConfigSchema.value = parseSchemaFromDevice(schema.value);
			deviceConfigProfile.value = parseProfileFromDevice(profile.value);
			schemaTree.root.properties = deviceConfigSchema.value;
			const applySchema = (value: any, path: string) => {
				//当前有相同Schema的key不执行
				// if (!jsonpath.query(deviceConfigSchema.value, assJsonpathData(path)).length) {
				let obj = jsonpath.query(deviceConfigSchema.value, assJsonpathData(path)).length
					? jsonpath.query(deviceConfigSchema.value, assJsonpathData(path))[0]
					: {};
				if (obj && JSON.stringify(obj) != "{}" && obj.type) {
					obj.type = obj.type || typeof value;
				}
				if (typeof value == "object" && obj && JSON.stringify(obj) != "{}" && obj.type && obj.type == "object") {
					jsonpath.value(deviceConfigSchema.value, assJsonpathData(path), { ...obj });
					for (let ck in value) {
						let cPath = path ? path + ".properties." + ck + "" : ck;
						jsonpath.value(deviceConfigSchema.value, assJsonpathData(cPath));
						applySchema(value[ck], cPath);
					}
				} else {
					jsonpath.value(deviceConfigSchema.value, assJsonpathData(path), { ...obj });
				}
				// }
			};
			for (let key in deviceConfigProfile.value) {
				applySchema(deviceConfigProfile.value[key], key);
			}
			delete deviceConfigSchema.value[SchemaNodeKey.sensor];
		};

		// const dialogVisible = ref<boolean>(false);
		return () => {
			return (
				<div class="block-basic p-8">
					{/* <DialogBox
						title="查看JSON"
						class="dialog-dense"
						v-model:visible={dialogVisible.value}
						footerLabel={["关闭"]}
						width="550px"
					>
						<JsonView profile={deviceConfigProfile.value} schema={schemaTree.root} />
					</DialogBox> */}
					<div class="flex mb-4 justify-between">
						<div class="flex">
							{/* <el-button type="primary" plain onClick={() => saveSchema()} disabled={disabledMod.value}>
								{proxy?.$t("deviceparam.btn.save")}
							</el-button> */}
							{/* <el-button type="primary" plain onClick={() => saveProfile()}>
								保存配置
							</el-button> */}
						</div>
						{/* <el-button class="ml-auto" link type="primary" onClick={() => (dialogVisible.value = true)}>
							预览JSON
						</el-button> */}
					</div>
					<JsonSchemaEditor
						class="w-full"
						value={schemaTree}
						lang="zh_CN"
						custom
						jsonValue={deviceConfigProfile.value}
						disabled={disabledMod.value}
					/>
				</div>
			);
		};
	}
});
